package org.cometmi.gwt.echo2.client;

import java.util.Date;

import org.cometmi.gwt.client.Connection;
import org.cometmi.gwt.echo2.shared.MyTestProxy;
import org.cometmi.gwt.shared.MiQueue;
import org.cometmi.gwt.shared.MiQueuePool;
import org.cometmi.gwt.shared.MiTransaction;
import org.cometmi.gwt.shared.events.BindCallback;
import org.cometmi.gwt.shared.exceptions.InvalidArgumentException;
import org.cometmi.gwt.shared.exceptions.NameParseException;
import org.cometmi.gwt.shared.request.var.ReturnVar;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;

public class Echo2Test implements EntryPoint
{
	Connection conn = Connection.INSTANCE;

	@Override
	public void onModuleLoad()
	{
		try
		{
			MiQueue qListen = conn.getQueue("org.cometmi.gwt.test.echo2");
			MiQueuePool qSend = conn.getQueue("org.cometmi.gwt.test.echo2");

			qListen.bind(new BindCallback()
			{
				@Override
				public void onSuccess()
				{}

				@Override
				public void onError(Throwable t)
				{
					Window.alert(t.getMessage());
				}
			});

			final MiTransaction t = qSend.createTransaction();
			final MyTestProxy proxy = t.proxyToNewObject(MyTestProxy.class, "costr str");

			final TextBox echoBox = new TextBox();

			Button sendButton = new Button("Send", new ClickHandler()
			{
				public void onClick(ClickEvent event)
				{
					try
					{
						ReturnVar<Date> date = proxy.myMethod1(echoBox.getValue());
						proxy.myMethod1(date);

						MyTestProxy copy = proxy.getCopy();
						copy.myMethod1("The copy of " + echoBox.getValue());

						MyTestProxy wrap = proxy.wrap(copy);
						wrap.myMethod1("The wrap of " + echoBox.getValue());

						t.commit();
					}
					catch (InvalidArgumentException e)
					{
						e.printStackTrace();
					}
				}
			});

			RootPanel.get().add(echoBox);
			RootPanel.get().add(sendButton);
		}
		catch (NameParseException e)
		{
			e.printStackTrace();
		}
		catch (InvalidArgumentException e)
		{
			e.printStackTrace();
		}
	}
}
